package controller;

import Model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import service.UserService;
import service.impl.UserServiceImpl;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        User user = null;
        try {
            user = userService.getUserByName(username);
            System.out.println("根据用户名查询的用户信息：\t" + user);
        } catch (SQLException e) {
            System.out.println("根据用户名查询数据库异常！！！");
            e.printStackTrace();
        }

        if (user != null) { //数据库中存在该用户

            if (user.getPassword().equals(password)) { // 校验密码
                // 勾选了记住我，设置Cookie
                if ("yes".equals(rememberMe)) {
                    Cookie usernameCookie = new Cookie("username", username);
                    Cookie passwordCookie = new Cookie("password", password);
                    usernameCookie.setMaxAge(60 * 60 * 24 * 7); // 设置Cookie的过期时间为7天
                    passwordCookie.setMaxAge(60 * 60 * 24 * 7); // 设置Cookie的过期时间为7天
                    response.addCookie(usernameCookie);
                    response.addCookie(passwordCookie);
                }
                // 将用户名存入会话中 跳转主页
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                response.sendRedirect(request.getContextPath() + "/home"); // 重定向到主页
            } else {
                // 验证失败 密码错误
                request.setAttribute("errorMessage", "密码错误！");
                getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
            }

        } else {// 验证失败 用户名不存在
            request.setAttribute("errorMessage", "用户名不存在请先注册！");
            getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}